//
//  LoadPageLocationController.m
//  MIT-AffordSuperMarket
//
//  Created by apple on 16/1/27.
//  Copyright © 2016年 河南大实惠电子商务有限公司. All rights reserved.
//

#import "LoadPageLocationController.h"
//untils
#import "Global.h"
#import "NSString+Conversion.h"
#import "ManagerHttpBase.h"
#import "ManagerGlobeUntil.h"
//baidu
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
//model
#import "XiaoQuAndStoreInfoModel.h"
@interface LoadPageLocationController ()
{
    BOOL _isYunJianSuoSuccess;
}
@property (nonatomic, weak) BMKMapView *mapView;
@property (nonatomic, strong) NSString *longitudeAndLatitudeStr;//经纬度
@property (nonatomic,strong) NSMutableArray *poiArray;//云检索返回商铺信息
@end

@implementation LoadPageLocationController

- (void)viewDidLoad {
    [super viewDidLoad];
    _poiArray = [[NSMutableArray alloc]init];
    [self setupBackgroundImage];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
    if ([ManagerGlobeUntil sharedManager].isNetworkReachability) {
        [self settingBaiDuKey];
        _locService.delegate = self;
    } else {//未联网判断定位失败
        [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEIFAILED object:nil];
    }
}
-(void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    _locService.delegate = nil;
    _search.delegate = nil;
}


- (void)setupBackgroundImage {
    NSString *imageName = @"";
    if (VIEW_HEIGHT == 480) {//4/4s
        imageName = @"Default";
    } else if (VIEW_HEIGHT == 568) {//5/5s
        imageName = @"Default-568";
    } else if (VIEW_HEIGHT == 667) {//6
        imageName = @"Default-750";
    } else if (VIEW_HEIGHT == 736) {//6p
        imageName = @"Default-1242";
    }
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:imageName]];
}
//设置百度key
- (void)settingBaiDuKey {
    
    [self settingMapViewParamer];
    [self settingLocationService];
}
//设置百度视图
- (void)settingMapViewParamer {
    [self.mapView setZoomLevel:14.0];
    _mapView.userTrackingMode = BMKUserTrackingModeNone;//设置定位的状态
}
//初始化BMKLocationService
- (void)settingLocationService {
    //初始化BMKLocationService
    _locService = [[BMKLocationService alloc]init];
    [_locService startUserLocationService];
}



#pragma mark -- 停止定位

-(void)StopLocating
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    [_locService stopUserLocationService];
}
#pragma mark -- BMKLocationServiceDelegate（百度定位）
/**
 *在地图View将要启动定位时，会调用此函数
 *@param mapView 地图View
 */
- (void)willStartLocatingUser
{
    NSLog(@"start locate");
}

/**
 *用户方向更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateUserHeading:(BMKUserLocation *)userLocation
{
    //[_mapView updateLocationData:userLocation];
    NSLog(@"heading is %@",userLocation.heading);
    
}

/**
 *用户位置更新后，会调用此函数
 *@param userLocation 新的用户位置
 */
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation
{
    
    //位置信息
    
    CLLocation *location =userLocation.location;
    // 拿到定位的经纬度
    NSString *x1 = [NSString stringWithFormat:@"%f", location.coordinate.longitude];
    NSString *y1 = [NSString stringWithFormat:@"%f", location.coordinate.latitude];
    NSString *z1 =@",";
    NSString  *string = [x1 stringByAppendingString:z1];
    _longitudeAndLatitudeStr = [string stringByAppendingString:y1];
    if (_longitudeAndLatitudeStr.length != 0) {
        [_locService setDelegate:nil];
        //启动云检索
        [self StartCloudSearch];
    }
    
}
/**
 *在地图View停止定位后，会调用此函数
 *@param mapView 地图View
 */
- (void)didStopLocatingUser {
    
}

/**
 *定位失败后，会调用此函数
 *@param mapView 地图View
 *@param error 错误号，参考CLError.h中定义的错误号
 */
- (void)didFailToLocateUserWithError:(NSError *)error{
    [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEIFAILED object:nil];
}
#pragma mark -- BMKCloudSearchDelegate（百度云检索）
//获取检索信息
-(void)onGetCloudPoiResult:(NSArray*)poiResultList searchType:(int)type errorCode:(int)error
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    if (error == BMKErrorOk) {
        BMKCloudPOIList* result = [poiResultList firstObject];
        [self.poiArray removeAllObjects];
        
        isDescend = NO;
        //对数据进行排序
        [self.poiArray addObjectsFromArray:[result.POIs sortedArrayUsingFunction:sortedarrayWithDistance context:NULL]];
        if ([self.poiArray count] != 0) {//判断云检索是否返回数据
            _isYunJianSuoSuccess = YES;
        }
        [self refreshDataSouce];
        
        
        
        
    } else {
        //检索失败发送通知
        [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEIFAILED object:nil];
        
    }
    
    
}
//获取云检索数据进行刷新table
- (void)refreshDataSouce {
    BMKCloudPOIInfo *poiInfo = (BMKCloudPOIInfo*)[self.poiArray firstObject];
    NSString *uID = [NSString stringISNull:[NSString stringWithFormat:@"%d",poiInfo.uid]];
    [self LoadXiaoQuInfoDataWithBaiDuUID:uID selected:NO xiaoQuName:poiInfo.title xiaoQuAddress:poiInfo.address shopName:[poiInfo.customDict objectForKey:@"shopName"]];
}



#pragma mark -- 开启周围云检索
//dGscuztU0zE131kfsxerHBcy   124311
-(void)StartCloudSearch
{
    //初始化云检索服务
    _search = [[BMKCloudSearch alloc]init];
    _search.delegate = self;
    
    //初始化对象
    BMKCloudNearbySearchInfo *cloudNearbySearch = [[BMKCloudNearbySearchInfo alloc]init];
    cloudNearbySearch.ak = BaiDuDingWeiServerKey;
    cloudNearbySearch.geoTableId = BaiDuDingWeiTableID;
    cloudNearbySearch.pageIndex = 0;
    cloudNearbySearch.pageSize = 10;
    //用的时候 把定位经纬度传过来
    cloudNearbySearch.location = _longitudeAndLatitudeStr;
    
    cloudNearbySearch.radius = BaiDuDingWeiRadius;
    cloudNearbySearch.keyword = BaiDuDingWeiKeyword;
    BOOL flag = [_search nearbySearchWithSearchInfo:cloudNearbySearch];
    if(flag)
    {
        NSLog(@"周边云检索发送成功");
    }
    else
    {
        [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEIFAILED object:nil];
        NSLog(@"周边云检索发送失败");
    }
    
}

#pragma mark -- requestData
- (void)LoadXiaoQuInfoDataWithBaiDuUID:(NSString*)uid selected:(BOOL)isSelected xiaoQuName:(NSString*)name xiaoQuAddress:(NSString*)address shopName:(NSString *)shopName{
    //保存小区UID
    
    //请求参数说明： SIGNATURE  设备识别码
    ManagerHttpBase *manager = [ManagerHttpBase sharedManager];
    NSMutableDictionary *parameter = [[NSMutableDictionary alloc]init];
    [parameter setObject:uid forKey:@"BAIDUKEY"];
    [manager parameters:parameter customPOST:@"common/location" success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if ([responseObject isKindOfClass:[NSDictionary class]]) {
            NSDictionary *dataDic = (NSDictionary*)responseObject;
            NSString *state = [NSString stringTransformObject:[dataDic objectForKey:@"STATE"]];//状态码
            if ([state isEqualToString:@"0"]) {//请求成功
                if (dataDic.count != 0) {
                    XiaoQuAndStoreInfoModel *model = [[XiaoQuAndStoreInfoModel alloc]init];
                    model.xiaoQuID = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"COMMUNITY"] objectForKey:@"ID"]];
                    model.xiaoQuName = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"COMMUNITY"] objectForKey:@"TITLE"]];
                    model.xiaoQuAddress = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"COMMUNITY"] objectForKey:@"ADDRESS"]];
                    model.storeID = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"ID"]];
                    model.storeName = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"TITLE"]];
                    model.storeAddress = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"ADDRESS"]];
                    model.storePhone = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"TEL"]];
                    NSString *storeStartTime = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"BEGINTIME"]];
                    NSString *storeEndTime = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"ENDTIME"]];
                    model.storeYingYeTime = [NSString stringWithFormat:@"%@-%@",storeStartTime,storeEndTime];
                    model.storePeiSongIntroduce = [NSString stringTransformObject:[[[dataDic objectForKey:@"OBJECT"] objectForKey:@"STORE"] objectForKey:@"DELIVERYDES"]];
                    [[ManagerGlobeUntil sharedManager] updataXiaoquAndStoreInfoWithModel:model];
                    [[NSNotificationCenter defaultCenter] postNotificationName:PRODUCTCOUNTCHANGE object:nil];
                    [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEISUCCESS object:nil];
                }
            }else {//请求失败
                [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEIFAILED object:nil];
            }
        }
        
    } failure:^(bool isFailure) {
        [[NSNotificationCenter defaultCenter] postNotificationName:DINGWEIFAILED object:nil];
        
    }];
}
#pragma mark -- 对云检索数据进行排序
bool isDescend; //是否降序
int ranktype;//列的类型

NSInteger sortedarrayWithDistance(id obj1, id obj2, void *context) {
    if ([obj1 isKindOfClass:[BMKCloudPOIInfo class]]&&[obj2 isKindOfClass:[BMKCloudPOIInfo class]])
    {
        BMKCloudPOIInfo *data1 = (BMKCloudPOIInfo*)obj1;
        BMKCloudPOIInfo *data2 = (BMKCloudPOIInfo*)obj2;
        float v1 = 0,v2 = 0;
        //根据当前类型取值
        if (ranktype != -1)
        {
            v1 = data1.distance;
            v2 = data2.distance;
        }
        
        if (v1 < v2)
        {
            return (isDescend ? NSOrderedDescending:NSOrderedAscending);
        }
        else if (v1 > v2)
        {
            return (isDescend ? NSOrderedAscending:NSOrderedDescending);
        }
        else
        {
            return NSOrderedSame;
        }
    }
    
    return NSOrderedSame;
}


- (void)dealloc {
    if (_mapView) {
        _mapView = nil;
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
